package com.biejiaogroup.librarymanager.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;


/**
 * @Description: Filter用于过滤未登录的请求
 * @Author: JesseChan
 * @Date: 2022/5/13
 */
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class loginFilter implements Filter {
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/login", "/login.jsp","/register.jsp","/register")));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取最后一个/后的路径
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");

        String servletPath = request.getServletPath();

        boolean allowedPath = ALLOWED_PATHS.contains(path);

        if (request.getSession().getAttribute("login") == null && !allowedPath && !servletPath.endsWith(".js") && !servletPath.endsWith(".css"))
        {
            response.sendRedirect("login.jsp");
        }
        else
        {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
